#!/usr/bin/env python
# coding=utf-8
##########################################################################
# Author: wangdj
# mail: wangdajunttf@163.com
# Created Time: Thu 28 Oct 2021 04:27:56 PM CST
##########################################################################

from time import gmtime
from time import strftime
import copy
import json
import os
import sys
import time
import re
from subprocess import Popen, PIPE, STDOUT, run
from rich import print, print_json
from rich.console import Console
console = Console()

# print sys.argv


# 执行 ffmpeg 命令不会卡住，实时输出
def run_shell(shell):
  print(':vampire:[bold magenta]$[/bold magenta]', shell)
  cmd = Popen(shell,
              stdin=PIPE,
              stderr=sys.stderr,
              close_fds=True,
              stdout=sys.stdout,
              universal_newlines=True,
              shell=True,
              bufsize=1)
  cmd.communicate()
  return cmd.returncode


# if __name__ == '__main__':
#  print(run_shell("ping www.baidu.com"))
# sys.exit()


# 执行 ffmpeg 命令会卡住不实时输出
def exe_command(command):
  """
  执行 shell 命令并实时打印输出
  :param command: shell 命令
  :return: process, exitcode
  """
  print(command)
  process = Popen(command,
                  stdout=PIPE,
                  stderr=STDOUT,
                  shell=True,
                  encoding="utf-8")
  with process.stdout:
    for line in process.stdout.readlines():
      print(line)
  exitcode = process.wait()
  return process, exitcode


# 执行 要等待的 命令会卡住不实时输出，可以拿到输出结果
def cmd(command):
  subp = Popen(command,
               shell=True,
               stdout=PIPE,
               stderr=PIPE,
               encoding="utf-8")
  subp.wait(5)
  if subp.poll() == 0:
    return subp.stdout.readlines()
  else:
    print('失败')


interval = 120
thisPath = os.path.split(os.path.realpath(__file__))[0]
jsonDataF = '/home/ttf08153/videoff'

videoFs = []
with open(jsonDataF, 'r', encoding='utf8') as f:
  videoFs = f.readlines()
print(videoFs)
# sys.exit()

imgUploadGd = f'ttfa:ffmpegImg/tttimg'

localGdP = '/pdmount'
localImgPath = '/gdup_image'

for fp in videoFs:
  fp = fp.strip()
  ffmpegReturnCode = run_shell(
      f"[ -f '{localGdP}/{fp}' ]"
  )
  if ffmpegReturnCode != 0:
    print('文件不存在！下一个！')
    continue

  fn = re.findall(r'[^/]+$', fp)[0]
  localImgP = f'{localImgPath}/{fn}'
  run_shell(f"mkdir -pv '{localImgP}'")

  ffmpegReturnCode = run_shell(
      f"bash {thisPath}/ffm.sh {interval} '{localGdP}/{fp}' '{localImgP}'"
  )
  if ffmpegReturnCode != 0:
    print('ffmpeg 生成图片出错！退出脚本！')
    break

  # 图片文件名，格式化处理下
  for imgF in os.listdir(localImgP):
    secSuffix = re.findall(r'^(\d+)(.+)', imgF)[0]
    sec = int(secSuffix[0])
    sfx = secSuffix[1]
    strfT = strftime("%H:%M:%S", gmtime(sec))
    os.system(f"mv '{localImgP}/{imgF}' '{localImgP}/{strfT}{sfx}'")

  # 上传图片
  imgUploadGdP = f'{imgUploadGd}/{fn}'
  uploadReturnCode = run_shell(
      f"rclone sync -v '{localImgP}' '{imgUploadGdP}'")
  if uploadReturnCode == 0:
    print('清除临时文件')
    run_shell(f"rm -rf '{localImgP}'")
  else:
    print('前面的命令出错啦，退出脚本！')
    break
